package me.seawenc.db.checker.dbengine;

import me.seawenc.db.checker.bean.FileConfig;
import me.seawenc.db.checker.dbengine.impl.engines.*;

import java.lang.reflect.Constructor;

/**
 * 数据源类型
 */
public enum DsType {
    POSTGRESQL(EngineServicePostgresql.class),
    HIVE(EngineServiceHive.class),
    MYSQL(EngineServiceMsyql.class),
    ORACLE(EngineServiceOracle.class),
    PRESTO(EngineServicePresto.class);
    private Class<? extends IEngineService> engineCLass;
    DsType(Class<? extends IEngineService> engineService){
        this.engineCLass =engineService;
    }

    public String lname(){
        return this.name().toLowerCase();
    }

    public static IEngineService findDbEngine(FileConfig fileConfig) throws Exception {
        DsType dsType = findTypeByDriver(fileConfig.getJdbcDriver());
        return dsType.getEngineService(fileConfig);
    }

    private IEngineService getEngineService(FileConfig parameters) throws Exception {
        Constructor<? extends IEngineService> constructor = this.engineCLass.getConstructor(FileConfig.class);
        IEngineService engineService = constructor.newInstance(parameters);
        return engineService;
    }

    /**
     * 如果驱动串中包含，关键字，则直接返回
     * @param dbDriver
     * @return
     */
    private static DsType findTypeByDriver(String dbDriver){
        for (DsType dsType:DsType.values()){
            if(dbDriver.contains(dsType.lname())){
                return dsType;
            }
        }
        return DsType.valueOf(dbDriver.toUpperCase());
    }


}
